package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.exception.QueryFailedException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.DeviceService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *	 类说明:设备资料业务层实现类
 *
 * @author XIET
 *
 * @version 创建时间：2018年12月3日 上午10:46:56
 */
@Service
public class DeviceServiceImpl implements DeviceService {

	private  static  final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);

	/**
	 * 注入mapper
	 */
	@Resource
	private DeviceDetailMapper deviceDetailMapper;
	@Resource
	private DeviceMapper deviceMapper;
	@Resource
	private InspectWorkMapper inspectWorkMapper;
	@Resource
	private MaintainPlanMapper maintainPlanMapper;
	@Resource
	private MaintainWorkMapper maintainWorkMapper;
	@Resource
	private RepairWorkMapper repairWorkMapper;
	@Resource
	private ScrapWorkMapper scrapWorkMapper;
	@Resource
    private StationMapper stationMapper;
	@Resource
	private UploadMapper uploadMapper;
	/**
	 * 查询设备资料
	 */
	@Override
	public JSONObject queryDevice(Device device,String startDate,String endDate,String maintainStartDate,String maintainEndDate) {
		//声明listDevice集合，用来装查询出来的参数
		List<Device> listDevice = null;
        try{
            Integer pagesize = device.getPagesize();
            Integer pageindex = device.getPageindex();
            if(pagesize != null && pageindex != null) {
                device.setIncept(pagesize*(pageindex - 1));
            }
			if(!org.apache.commons.lang3.StringUtils.isEmpty(startDate)){
				try {
					Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDate);
				} catch (ParseException e) {
					return JSONObject.build(JSONObject.ERROR,"进厂开始日期格式错误");
				}
			}
			if(!org.apache.commons.lang3.StringUtils.isEmpty(endDate)){
				try {
					Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate);
				} catch (ParseException e) {
					return JSONObject.build(JSONObject.ERROR,"进厂结束日期格式错误");
				}
			}
			if(!org.apache.commons.lang3.StringUtils.isEmpty(maintainStartDate)){
				try {
					Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(maintainStartDate);
				} catch (ParseException e) {
					return JSONObject.build(JSONObject.ERROR,"保养开始日期格式错误");
				}
			}
			if(!org.apache.commons.lang3.StringUtils.isEmpty(maintainEndDate)){
				try {
					Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(maintainEndDate);
				} catch (ParseException e) {
					return JSONObject.build(JSONObject.ERROR,"保养日期格式错误");
				}
			}
            listDevice = deviceMapper.listDevice(device,startDate,endDate,maintainStartDate,maintainEndDate);
            //判断查询出来的集合是否为空
            if(listDevice.isEmpty()) {
                return JSONObject.oK("没有设备资料相关数据", listDevice, 0);
            }
            //用来记录查询出来的条数
            int count = deviceMapper.countDevice(device,startDate,endDate,maintainStartDate,maintainEndDate);
            return JSONObject.oK("查询成功", listDevice, count);
        }catch(GlobalException e){//捕获自定义异常
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
	}

	/**
	 * 删除设备资料
	 */
	@Override
	public JSONObject deleteDevice(Long[] deviceIds, Integer dataState) {
		try{
			//判断传入的参数是否为null
			if(dataState == null) {
				//为null抛出异常
				throw new ParamsErrorException("数据状态不能为空");
			}else if(dataState != 1 && dataState != 2 && dataState != 3) {
	            throw new ParamsErrorException("数据状态错误");
	        }
			if(deviceIds == null || deviceIds.length == 0) {
				throw new ParamsErrorException("请选择设备资料");
			}
			if(dataState == 2){
				int i = inspectWorkMapper.selectByDeviceId(deviceIds);
				if(i>0){
					throw new ParamsErrorException("设备正在被点检作业使用");
				}
				int j = maintainPlanMapper.selectByDeviceId(deviceIds);
				if(j>0){
					throw new ParamsErrorException("设备正在被保养计划使用");
				}
				int k = maintainWorkMapper.selectByDeviceId(deviceIds);
				if(k>0){
					throw new ParamsErrorException("设备正在被保养作业使用");
				}
				int l = repairWorkMapper.selectByDeviceId(deviceIds);
				if(l>0){
					throw new ParamsErrorException("设备正在被维修作业使用");
				}
				int m = scrapWorkMapper.selectByDeviceId(deviceIds);
				if(m>0){
					throw new ParamsErrorException("设备正在被报废作业使用");
				}
			}
			//调用删除的接口
			int row = deviceMapper.deleteDevice(deviceIds,dataState);
			//声明msg字符串，用来存抛出的异常
			String msg = "";
	        if (row == 0) {
	            // 判断传入的数据状态参数dataState,返回相应信息
	            switch (dataState) {
	                case 1:
	                    throw new ModifyFailedException("启用失败");
	                case 2:
	                    throw new ModifyFailedException("删除失败");
	                case 3:
	                    throw new ModifyFailedException("停用失败");
	                default:
	                	break;
	            }
	        } else {
	            switch (dataState) {
	                case 1:
	                    msg = "启用成功";break;
	                case 2:
	                    msg = "删除成功";
						int row1 = deviceDetailMapper.deleteDetailByDeviceId(deviceIds);
	                    break;
	                case 3:
	                    msg = "停用成功";break;
	                default:
	                	break;
	            }
	        }
	        return JSONObject.oK(msg);
		}catch(GlobalException e) {
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 插入设备资料
	 */
	@Override
	public JSONObject insertDevice(Device device) {
		try {
			//判断传入的参数是否为null
			if(device.getDeviceId()!=null) {
				//为null则抛出异常
				throw new ParamsErrorException("新增设备资料时不能有id");
			}
			if(device.getRemark()==null){
				device.setRemark("");
			}
			checkParam(device);
			checkNoRepeat(device);
			/**
			 * @author: louk
			 * @param:
			 * @Return:
			 * @Description: :根据工位Id获取工位的名称
			 * @date: 2019/9/5 13:23
			 *
			 */
            Integer lStationId = device.getStationId();
            List<Station> station = stationMapper.getStation(lStationId);
            String staName = station.get(0).getStationName();
            device.setStationName(staName);
            //调用新增接口
			int row = deviceMapper.insertSelective(device);
			if(row == 0) {
				throw new ModifyFailedException("新增设备资料失败");
			}
			return JSONObject.oK("新增成功");
		}catch(GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 修改设备资料
	 */
	@Override
	public JSONObject updateDevice(Device device) {
		try {
			//判断传入的参数是否为null
			if(device.getDeviceId()==null) {
				//为null则抛出异常
				throw new ParamsErrorException("修改设备资料id不能为空");
			}
			if(device.getRemark()==null){
				device.setRemark("");
			}
			checkParam(device);
			checkNoRepeat(device);

			/**
			 * @author: louk
			 * @param:
			 * @Return:
			 * @Description: :根据工位Id获取工位的名称
			 * @date: 2019/9/5 13:23
			 *
			 */
            Integer lStationId = device.getStationId();
            List<Station> station = stationMapper.getStation(lStationId);
            if(station==null){
                throw new ModifyFailedException("工位不能为空");
            }
            String staName = station.get(0).getStationName();
            device.setStationName(staName);
            // 根据周期修改下次保养时间
			if(device.getMaintainDate() != null && device.getMaintainDate() != ""){
				try {
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String str = device.getMaintainDate();
					Date dt = sdf.parse(str);
					Calendar rightNow = Calendar.getInstance();
					rightNow.setTime(dt);
					rightNow.add(Calendar.MONTH,device.getMaintainPeriod());//日期加保养周期 月
					Date dt1=rightNow.getTime();
					String reStr = sdf.format(dt1);
					device.setNmaintainDate(reStr);
				} catch (Exception e){
				}
			}
			//调用修改的接口
			int row = deviceMapper.updateByPrimaryKeySelective(device);
			if(row == 0) {
				throw new ModifyFailedException("编辑失败");
			}
			return JSONObject.oK("编辑成功");
		}catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 查询工位
	 */
	@Override
	public JSONObject queryLStation(Integer lProductionLineId) {
		//声明listLStation集合，用来装查询出来的参数
		List<Integer> listLStation = null;
		try {
			//判断传入的参数是否为null
			if(lProductionLineId==null) {
				//为null则抛出异常
				throw new ParamsErrorException("请输入产线id");
			}
			//调用查询接口
			listLStation = deviceMapper.listLStation(lProductionLineId);
			//判断查出来的list集合是否为空
			if(listLStation.isEmpty()) {
				//为null则抛出异常
				throw new QueryFailedException("没有相关信息");
			}
			return JSONObject.build(200, "查询成功", listLStation);
		}catch (GlobalException e) {//捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	/**
	 * 根据编码查重
	 * @return
	 */
	@Override
	public Device getByDeviceCode(Device device) {
		return deviceMapper.getByDeviceCode(device);
	}



	public void checkParam(Device device){
		if(StringUtils.isEmpty(device.getDeviceName())){
			throw new ParamsErrorException("设备名称不能为空");
		}
		if(device.getDeviceName().length()>50){
			throw new ParamsErrorException("设备名称长度不能大于50");
		}
		if(StringUtils.isEmpty(device.getDeviceCode())){
			throw new ParamsErrorException("设备编码不能为空");
		}
		if(device.getDeviceCode().length()>50){
			throw new ParamsErrorException("设备编码长度不能大于50");
		}
		if(getByDeviceCode(device) != null){
			throw new ParamsErrorException("编码已存在");
		}
		if(device.getRemark().length()>100){
			throw new ParamsErrorException("说明的备注长度不能大于100");
		}
		if(device.getDeviceTypeId()==null){
			throw new ParamsErrorException("设备类型不能为空");
		}
		if(device.getStationId()==null){
			throw new ParamsErrorException("请选择工位");
		}
		if(device.getProductlineId()==null){
			throw new ParamsErrorException("请选择产线");
		}
		if(device.getMaintainPeriod() == null){
			throw new ParamsErrorException("设备保养周期不能为空");
		}
	}
	public  void checkNoRepeat(Device device){
		int count=deviceMapper.selectByDeviceName(device);
		if(count>0){
			throw new ParamsErrorException("设备名称不能重复");
		}
	}

	@Override
	public String checkNoRepeatExcel(Device device) {
		//产线名城
		String vcProductionLineName = device.getProductlineName();
		//工位名称
		String lStationName = device.getStationName();
		//设备类型
		String typeName = device.getDeviceTypeName();
        Integer maintainPeriod = device.getMaintainPeriod();
        //mac地址
        String macIp = device.getMacIp();
        if(StringUtils.isEmpty(device.getDeviceName()) && StringUtils.isEmpty(device.getDeviceCode())
		&& StringUtils.isEmpty(vcProductionLineName) && StringUtils.isEmpty(lStationName) && StringUtils.isEmpty(typeName) && (maintainPeriod==null || "".equals(maintainPeriod)) ){
			return "该行数据为空/删除不彻底";
		}
		if(StringUtils.isEmpty(device.getDeviceName())){
			return "设备名称不能为空";
		}
		if(device.getDeviceName().getBytes().length>50){
			return "设备名称长度不能大于50个字节,25个汉字";
		}
		if(StringUtils.isEmpty(device.getDeviceCode())){
			return "设备编码不能为空";
		}
		if(device.getDeviceCode().getBytes().length>50){
			return "设备编码长度不能大于50个字节,25个汉字";
		}
		if(getByDeviceCode(device) != null){
			return "编码已存在";
		}
		int count=deviceMapper.selectByDeviceName(device);
		if(count>0){
			return "设备名称已存在";
		}
		if(StringUtils.isEmpty(vcProductionLineName)){
			return "产线名称为空";
		}
		if(maintainPeriod==null || "".equals(maintainPeriod)){
		    return "保养周期不能为空且必须为整数";
        }
		//获取所有产线
		Map<String, Productline> productLineMap = uploadMapper.queryProductLine();
		if(!productLineMap.containsKey(vcProductionLineName)){
			return "产线名称填写错误/不规范";
		}
		Productline productLine = productLineMap.get(vcProductionLineName);
		Integer lProductionLineId = productLine.getProductlineId();
		device.setProductlineId(lProductionLineId);
		if(StringUtils.isEmpty(lStationName)){
			return "工位名称为空";
		}
		Map<String, Station> stationMap = uploadMapper.queryStation();
		if(!stationMap.containsKey(lStationName)){
			return "工位名称填写错误/不规范";
		}
		Station station = stationMap.get(lStationName);
		if(!station.getProductlineId().equals(lProductionLineId)){
			return "填写工位名称不属于所填写的产线";
		}
		device.setStationId(station.getStationId());

		Map<String, DeviceType> deviceTypeMap = uploadMapper.queryDeviceType();
		if(!deviceTypeMap.containsKey(typeName)){
			return "类型名称填写不规范/错误";
		}
		DeviceType deviceType = deviceTypeMap.get(typeName);
		device.setDeviceTypeId(deviceType.getDeviceTypeId());
		if(!StringUtils.isEmpty(macIp) && macIp.getBytes().length>50){
		    return "mac地址的长度不能超过50";
        }
		return null;
	}

	@Override
	public JSONObject updateListDevice(List<Device> deviceList) {
		uploadMapper.updateListDevice(deviceList);
		return null;
	}

}
